<?php

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

if(empty($_REQUEST['act']))
{
	$_REQUEST['act'] = 'login';
}
else 
{
	$_REQUEST['act'] = trim($_REQUEST['act']);
}

$exc = new exchange($ecs->table("admin_user"),$db,'user_id','user_name');

if($_REQUEST['act'] == 'logout')
{
	setcookie('ECSCP[admin_id]','',1);
	setcookie('ECSCP[admin_pass]','',1);
	
	$sess->destroy_session();
	$_REQUEST['act'] = 'login';
}



if($_REQUEST['act'] == 'login')
{
	header("Expires: Mon,26 Jul 1997 05:00:00 GMT");
	header("Cache-Control: no-cache,must-revalidate");
	header("Pragma: no-cache");
	
	if((intval($_CFG['captcha']) & CAPTCHA_ADMIN) && gd_version() > 0)
	{
		$smarty->assign('gd_version',gd_version());
		$smarty->assign('random',mt_rand());
	}
	
	$smarty->display('login.html');
}
elseif($_REQUEST['act'] == 'signin')
{
	if(!empty($_SESSION['captcha_word']) && (intval($_CFG['captcha']) & CAPTCHA_ADMIN))
	{
		include_once ROOT_PATH . 'includes/cls_captcha.php';
		
		$validator = new captcha();
		if(!empty($_POST['captcha']) && !$validator->check_word($_POST['captcha']))
		{
			sys_msg($_LANG['captcha_error'],1);
		}
	}
	
	$_POST['username'] = isset($_POST['username']) ? trim($_POST['username']) : '';
	$_POST['password'] = isset($_POST['password']) ? trim($_POST['password']) : '';
	
	$sql = "SELECT user_id,user_name,password,last_login,action_list,last_login,suppliers_id ".
			" FROM ". $ecs->table('admin_user') .
			" WHERE user_name = '" . $_POST['username'] ." ' AND password = '" . md5($_POST['password']) . "'";
	
	$row = $db->getRow($sql);

	if($row)
	{
		set_admin_session($row['user_id'],$row['user_name'],$row['action_list'],$row['last_login']);
		$_SESSION['suppliers_id'] = $row['suppliers_id'];
		
		if($row['action_list'] == 'all' && empty($row['last_login']))
		{
			$_SESSION['shop_guide'] = true;
		}
		
		$db->query("UPDATE " .$ecs->table('admin_user') . " SET last_login='" . gmtime() . "',last_ip = '" . real_ip() . "'".
					" WHERE user_id = '$_SESSION[admin_id]'");
		
		if(isset($_POST['remember']))
		{
			$time = gmtime() + 3600*24*365;
			setcookie('ECSCP[admin_id]',$row['user_id'],$time);
			setcookie('ECSCP[admin_pass]',md5($row['password'] . $_CFG['hash_code']),$time);
		}
		
//		clear_cart();

		ecs_header("Location: ./index.php\n");
		exit;
	}
	else 
	{
		sys_msg($_LANG['login_faild'],1);
	}
}




